import { PlusOutlined } from '@ant-design/icons';
import { Button, Divider, message, Select, Popconfirm, TreeSelect } from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import CreateForm from './components/CreateForm';
import FormItem from 'antd/lib/form/FormItem';
import styles from '../../global.less';
import { CloseOutlined } from '@ant-design/icons';
import {
  queryRule,
  updateRule,
  addRule,
  removeRule,
  queryStore,
  queryPosition,
  getDictionary,
} from './service';
import { transTitle } from '@/utils/utils';
import EditTableStore from './components/EditTableStore';
import Access from '@/components/Access/Access';
/**
 * 添加节点
 *
 * @param fields
 */

const handleAdd = async (fields) => {
  const hide = message.loading('正在添加');

  try {
    await addRule({ ...fields });
    hide();
    message.success('添加成功');
    return true;
  } catch (error) {
    hide();
    message.error('添加失败请重试！');
    return false;
  }
};
/**
 * 更新节点
 *
 * @param fields
 */

const handleUpdate = async (fields) => {
  const hide = message.loading('正在修改');

  try {
    await updateRule({ ...fields });
    hide();
    message.success('修改成功');
    return true;
  } catch (error) {
    hide();
    message.error('修改失败请重试！');
    return false;
  }
};
/**
 * 删除节点
 *
 * @param selectedRows
 */

const handleRemove = async (selectedRows, actionRef) => {
  const hide = message.loading('正在删除');
  if (!selectedRows) return true;

  try {
    await removeRule(selectedRows.id);
    hide();
    message.success('删除成功，即将刷新');
    actionRef.current.reload();
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};

const TableList = () => {
  Array.prototype.remove = function (val) {
    for (var i = 0; i < this.length; i++) {
      if (this[i] == val) this.splice(i, 1);
    }
  };
  const [createModalVisible, handleModalVisible] = useState(false);
  const [editModalVisible, handleEditModalVisible] = useState(false);
  const [editFormValues, setEditFormValues] = useState({});
  const [treeValue, handleTreeValue] = useState();
  const [menuValues, setMenuValues] = useState([]);
  const actionRef = useRef();
  const [storeValue, setStoreValue] = useState([]);
  const [storeArr, setStoreArr] = useState([]);
  const [children, setChildren] = useState([]);
  const [positionId, setPositionId] = useState();
  const [Selected, setSelected] = useState([]);
  const [selectedArray, setSelectedArray] = useState([]);
  const [showKey, setShowKey] = useState([]);
  const [province, setProvince] = useState([]);
  const [city, setCity] = useState([]);
  const [area, setArea] = useState([]);
  const [show, setShow] = useState(true);
  const [areaState, setAreaState] = useState(true);
  const [cityState, setCityState] = useState(true);
  const handleGetStore = async (state) => {
    try {
      const { data } = await queryStore();
      state ? null : transTitle(data);
      setStoreArr(data);
    } catch (error) {
      return false;
    }
  };

  const findNode = (row, storeList) => {
    let list = [];
    storeList.forEach((obj) => {
      if (obj.id == row.storeId) {
        obj.commission = row.commission;
      } else {
        if (obj.children && obj.children.length > 0) {
          let children = findNode(row, obj.children);
          obj.children = children;
        }
      }
      list.push(obj);
    });
    return list;
  };
  const handleGetPostion = (params) => {
    queryPosition(params).then((res) => {
      if (res.data) {
        const {
          data: { positionStoreList, provinceId, cityId, areaId },
        } = res;
        if (positionStoreList) {
          positionStoreList.map((item, index) => {
            item.name = item.storeName;
            item.id = item.storeId;
            const list = findNode(item, storeArr);
            if (index === positionStoreList.length - 1) {
              return list;
            }
          });
          const checkList = positionStoreList.map((item) => {
            return (item = item.storeId);
          });
          setStoreArr(positionStoreList);
          setChildren(checkList);
          setSelected(positionStoreList);
        } else {
          setStoreArr([]);
          setChildren([]);
          setSelected([]);
        }
      } else {
        message.info('查询暂无关联信息!');
      }
    });
  };
  const TreeOnChange = (value, label, extra) => {
    handleTreeValue(label.id);
  };
  const handleCommissionChild = (value) => {
    const list = JSON.parse(JSON.stringify(storeValue));
    list.map((item) => {
      if (item.storeId === value.id) {
        if (value.id === item.storeId) {
          item.commission = value.commission;
        }
      }
    });
    Selected.map((item) => {
      item.id === value.id
        ? ((item.commission = value.commission), (item.positionId = positionId))
        : null;
    });
    setStoreValue(list);
  };
  const handleSort = (arr, keyState) => {
    for (let index = 0; index < arr.length; index++) {
      for (var j = index + 1; j < arr.length; j++) {
        if (keyState) {
          if (arr[index] == arr[j]) {
            arr.splice(j, 1);
            j--;
          }
        } else {
          if (arr[index] && arr[j]) {
            if (arr[index].id == arr[j].id) {
              arr.splice(j, 1);
              j--;
            }
          }
        }
      }
    }
    return arr;
  };

  const searchStateFun = () => {
    setSelectedArray(Selected);
  };
  const handleChildrenkey = (payload, arr, newKey) => {
    payload.map((item, index) => {
      arr.push({
        commission: item.commission,
        storeId: item.id,
        positionId: payload.positionId,
        storeName: item.name,
        contacts: item.contacts,
        id: item.id,
      });
      newKey.push(item.id);
      if (item.children) {
        handleChildrenkey(item.children, arr, newKey);
      }
    });
    return arr, newKey;
  };
  const StoreSelect = (record, selected, selectedRows) => {
    if (selected){
      const list = [record.id];
      setChildren(list.concat(children));
      const selectList = [record];
      setSelected(Selected.concat(selectList));
    }else{
      setChildren(children.filter(id=>id!==record.id));
      setSelected(Selected.filter(data=>data.id!==record.id));
    }
  };

  const StoreSelectAll = (selected, selectedRows, changeRows) => {
    setChildren(selectedRows.map(record=>record.id))
    const list = [];
    setSelected(list.concat(selectedRows));
  };
  const handleSendData = (payload) => {
    let arr = [];
    payload.map((item, index) => {
      arr.push({
        commission: item.commission,
        storeId: item.id,
        positionId: positionId ? positionId : '',
        storeName: item.name,
        contacts: item.contacts,
        id: item.id,
      });
    });
    return arr;
  };
  const getProvince = () => {
    getDictionary('province').then((res) => {
      if (res.code === 0) {
        const { data } = res;
        setProvince(data);
      }
    });
    getDictionary('city').then((res) => {
      if (res.code === 0) {
        const { data } = res;
        setCity(data);
      }
    });
    getDictionary('area').then((res) => {
      if (res.code === 0) {
        const { data } = res;
        setArea(data);
      }
    });
  };
  const handleProvince = (value, index) => {
    value
      ? getDictionary('city', value).then((res) => {
          if (res.code === 0) {
            const { data } = res;
            if (data.length === 0) {
              setShow(false);
            } else {
              setShow(true);
              setCity(data);
              setCityState(false);
            }
          }
        })
      : setCityState(true);
  };

  const handleCity = (value, index) => {
    getDictionary('area', value).then((res) => {
      if (res.code === 0) {
        const { data } = res;
        setArea(data);
        setAreaState(false);
      }
    });
  };
  const handleArea = (value) => {};

  const { Option } = Select;
  const columns = [
    {
      title: '职位',
      dataIndex: 'name',
      formItemProps: {
        rules: [
          {
            required: true,
            message: '职位为必填项',
          },
        ],
      },
    },
    {
      title: '父级',
      dataIndex: 'parentId',
      hideInTable: true,
      hideInSearch: true,
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        return (
          <FormItem label={false} className="formItem_div">
            <TreeSelect
              showSearch
              value={treeValue}
              dropdownStyle={{ maxHeight: 800, overflow: 'auto' }}
              placeholder="请选择父级"
              allowClear
              treeDataSimpleMode
              treeData={menuValues}
              treeNodeFilterProp="title"
              treeNodeLabelProp="title"
              onSelect={TreeOnChange}
            />
          </FormItem>
        );
      },
    },
    {
      title: '管辖省',
      dataIndex: 'provinceId',
      valueType: 'text',
      hideInSearch: true,
      hideInTable: true,
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        return (
          <Select placeholder="请选择所在省" allowClear onSelect={handleProvince}>
            {province.map((item_, index) => {
              return (
                <Option value={item_.id} key={item_.id}>
                  {item_.name}
                </Option>
              );
            })}
          </Select>
        );
      },
    },
    {
      title: '管辖市',
      dataIndex: 'cityId',
      hideInSearch: true,
      valueType: 'text',
      hideInTable: true,
      hideInForm: !show,
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        return (
          <Select placeholder="请选择所在市" disabled={cityState} allowClear onSelect={handleCity}>
            {city.map((item_, index) => {
              return (
                <Option value={item_.id} key={item_.id}>
                  {item_.name}
                </Option>
              );
            })}
          </Select>
        );
      },
    },
    {
      title: '管辖区',
      dataIndex: 'areaId',
      valueType: 'text',
      hideInSearch: true,
      hideInTable: true,
      hideInForm: !show,
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        return (
          <Select
            placeholder="请选择所在区县"
            allowClear
            disabled={areaState}
            onSelect={handleArea}
          >
            {area.map((item_, index) => {
              return (
                <Option value={item_.id} key={item_.id}>
                  {item_.name}
                </Option>
              );
            })}
          </Select>
        );
      },
    },

    {
      title: '额外管辖店铺',
      dataIndex: 'positionStoreList',
      hideInSearch: true,
      hideInTable: true,
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        return (
          <EditTableStore
            dataSource={storeArr}
            onSelect={StoreSelect}
            onSelectAll={StoreSelectAll}
            handleChildren={children}
            childrenCommission={handleCommissionChild}
            searchState={searchStateFun}
            CommissionState={false}
          />
        );
      },
    },
    {
      title: '已选中店铺',
      dataIndex: 'selected',
      hideInSearch: true,
      hideInTable: true,
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        return (
          <div className="selected_div">
            {Selected.map((item, index) => {
              return (
                <div key={index} className="store_selected">
                  <span>{item.name}</span>
                  <Popconfirm
                    title="确定删除该店铺吗?"
                    onConfirm={() => {
                      const handleId = JSON.parse(JSON.stringify(children));
                      const list = JSON.parse(JSON.stringify(Selected));
                      list.map((item_, index) => {
                        if (item.id === item_.id) {
                          return list.splice(index, 1);
                        }
                      });
                      handleId.map((item_, index) => {
                        if (item.id === item_) {
                          return handleId.splice(index, 1);
                        }
                      });
                      setSelected(list);
                      setChildren(handleId);
                    }}
                    okText="是"
                    cancelText="否"
                  >
                    <CloseOutlined style={{ color: 'red', cursor: 'pointer' }} />
                  </Popconfirm>
                </div>
              );
            })}
          </div>
        );
      },
    },

    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => {
        return (
          <>
            <Access accessKey={"@updatePosition"}>
              <a
                onClick={() => {
                  handleEditModalVisible(true);
                  handleTreeValue(record.parentId);
                  setEditFormValues(record);
                  handleGetPostion(record.id);
                  setPositionId(record.id);
                  setCityState(false);
                  setAreaState(false);
                }}
              >
                修改
              </a>
              <Divider type="vertical" />
            </Access>
            <Access accessKey={"@deletePosition"}>
              <Popconfirm
                title="确定删除职位吗?"
                onConfirm={() => {
                  handleRemove(record, actionRef);
                }}
                okText="是"
                cancelText="否"
              >
                <a>删除</a>
              </Popconfirm>
            </Access>

          </>
        );
      },
    },
  ];
  return (
    <PageContainer>
      <ProTable
        headerTitle="职位列表"
        actionRef={actionRef}
        rowKey="id"
        bordered
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Access accessKey={"@newPosition"}>
            <Button
              type="primary"
              onClick={() => {
                handleModalVisible(true);
                setEditFormValues({});
                setChildren([]);
                setStoreArr([]);
                setSelected([]);
                setSelectedArray([]);
              }}
            >
              <PlusOutlined /> 新建
            </Button>
          </Access>
          ,
        ]}
        request={(params, sorter, filter) => queryRule({ ...params, sorter, filter })}
        postData={(payload) => {
          transTitle(payload);
          setMenuValues(payload);
          let newExpandedKeys = [];
          const handleShowkey = (payload) => {
            payload.map((item, index) => {
              newExpandedKeys.push(item.id);
              if (item.children) {
                return handleShowkey(item.children);
              }
            });
            return newExpandedKeys;
          };
          setShowKey(handleShowkey(payload));
          handleGetStore();
          getProvince();
          return payload||[];
        }}
        columns={columns}
        expandable={{
          expandedRowKeys: showKey,
          onExpandedRowsChange: (e) => {
            setShowKey(e);
          },
        }}
        rowSelection={false}
        pagination={{
          defaultPageSize: 30,
          showSizeChanger: false,
          showTitle: false,
          showTotal: (total) => `共${total}条`,
        }}
      />
      <CreateForm
        title="新增职位"
        width={800}
        onCancel={() => handleModalVisible(false)}
        modalVisible={createModalVisible}
      >
        <ProTable
          className={styles.formBottom}
          onSubmit={async (value) => {
            const array = JSON.parse(JSON.stringify(Selected));
            const list = handleSendData(array);
            value.positionStoreList = list;
            value.parentId = treeValue;
            const success = await handleAdd(value);
            if (success) {
              handleModalVisible(false);

              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          rowKey="id"
          bordered
          form={{
            layout: 'horizontal ',
            labelAlign: 'rihgt',
            labelCol: { span: 4 },
            wrapperCol: { span: 24 },
          }}
          type="form"
          columns={columns}
        />
      </CreateForm>
      <CreateForm
        title="修改职位"
        onCancel={() => handleEditModalVisible(false)}
        modalVisible={editModalVisible}
        width={800}
      >
        <ProTable
          className={styles.formBottom}
          onSubmit={async (value) => {
            const array = JSON.parse(JSON.stringify(Selected));
            const list = handleSendData(array);
            list.map((item) => {
              return delete item.id;
            });
            value.positionStoreList = list;
            value.parentId = treeValue;
            value.id = editFormValues.id;
            const success = await handleUpdate(value);
            if (success) {
              handleEditModalVisible(false);
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          rowKey="id"
          bordered
          type="form"
          columns={columns}
          form={{
            initialValues: editFormValues,
            layout: 'horizontal',
            labelAlign: 'rihgt',
            labelCol: { span: 4 },
            wrapperCol: { span: 24 },
          }}
        />
      </CreateForm>
    </PageContainer>
  );
};

export default TableList;
